package com.neuedu.wemall.member.web.Intereptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.neuedu.wemall.common.util.RedisUtils;
import com.neuedu.wemall.common.util.SignUtils;
import com.neuedu.wemall.common.vo.ResponseData;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;

import static com.alibaba.fastjson.serializer.SerializerFeature.*;

/**
 * 登录检查拦截器
 */
@Log4j2
@Component
public class LoginCheckedInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtils redis;
    //令牌失效时间
    @Value("${config.token.expire}")
    private int expire;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        log.debug("当前请求路径为:" + url);
        String clientToken = getRequestToken(request);
        if (StrUtil.isEmpty(clientToken)) {
            //如果没有令牌,则放行(商品搜索、商品详情、登录、注册等无需token)
            return true;
        }
        //如果传递了令牌,则判断令牌是否已过期
        String tokenKey = SignUtils.getTokenKey(clientToken);
        if (!redis.hasKey(tokenKey)) {
            printMessage(ResponseData.fail(999, "令牌已过期或无效的令牌"), response);
            return false;
        }
        //判断是否合法token,即token是不是会员本人的token,是否盗用其他会员用户token或token有没有被篡改
        String signStr = redis.get(tokenKey).toString();
        if (!SignUtils.validateToken(clientToken, signStr, request)) {
            printMessage(ResponseData.fail(999, "非法的令牌,请重新登录获取令牌"), response);
            return false;
        }
        //如果已登录,延长令牌key、登录邮箱key有效期
        redis.expire(tokenKey, expire);
        String email = SignUtils.getAccount(signStr);
        String loginKey = SignUtils.getLoginKey(email);
        redis.expire(loginKey, expire);
        //如果令牌合法,则放行
        return true;
    }

    /**
     * 向客户端输出错误提示信息
     *
     * @param data
     */
    private void printMessage(ResponseData data, HttpServletResponse response) throws IOException {
        //向客户端输出JSON格式的数据
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = null;
        out = response.getWriter();
        String printText = JSONObject.toJSONStringWithDateFormat(data, "yyyy-MM-dd HH:mm:ss", WriteNullBooleanAsFalse,
                WriteNullListAsEmpty,
                WriteNullStringAsEmpty,
                WriteNullNumberAsZero,
                WriteDateUseDateFormat,
                WriteMapNullValue,
                PrettyFormat,
                DisableCircularReferenceDetect,
                BrowserCompatible);
        out.print(printText);
    }

    /**
     * 从请求中获取令牌
     *
     * @param request
     * @return
     */
    private String getRequestToken(HttpServletRequest request) {
        String token = request.getParameter("token");
        if (token == null) {
            token = request.getHeader("wemall-token");
        }
        return token;
    }
}
